class PartPurchasesController < ApplicationController
  before_action :set_menu

  def index
    @submenu = :part_purchase
    @title = '配件采购单'
    @tasks_grid = initialize_grid(PartPurchase, per_page: 8, order: 'id', order_direction: 'desc')
  end

  def new
    @title = "配件采购单/新增"
    @buttons.push :action => part_purchases_path, :label => "返回"
    @part_purchase = PartPurchase.new
    @suppliers = Supplier.all
  end

  def create
    @part_purchase = PartPurchase.new post_params
    if @part_purchase.save
      redirect_to part_purchase_path(:id => @part_purchase.id)
    else
      render :action => 'new'
    end
  end

  def show
    @title = "配件采购单/明细"
    @buttons.push :action => part_purchases_path, :label => "返回"
    @part_styles = PartStyle.all
    @part_purchase = PartPurchase.find params[:id]
    @tasks_grid = initialize_grid(Part, per_page: 5, order: 'id', order_direction: 'desc')
    if params.has_key? :new_part
      @part = Part.create(part_style_id: params[:part_style_id], code: params[:code], name: params[:name], unit: params[:unit], purchase_price: params[:purchase_price], sales_price: params[:sales_price])
      if @part.errors.full_messages == []
        @part_purchase.part_purchase_details.create(part_id: @part.id, qty: params[:qty])
        redirect_to part_purchase_path
      else
        @infos.push @part.errors.full_messages
      end
    end
    if params.has_key? :save
      if @part_purchase.part_purchase_details.blank?
        @infos.push "请增加明细"
      else
        @part_purchase.update_purchase_status
        redirect_to part_purchases_path
      end
    end
  end

  def destroy
    @part_purchase = PartPurchase.find params[:id]
    @part_purchase.destroy
    redirect_to part_purchases_path
  end


  def post_params
    params.require(:part_purchase).permit(*%w(note user_id supplier_id))
  end

  private
  def set_menu
    @mainmenu = :part
  end
end
